package handlers

import (
	"github.com/gin-gonic/gin"
	"perm-guard/models"
	"perm-guard/pkg"
	"strconv"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户名密码不能为空",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不正确",
		})
		return
	}
	if len(password) > 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func Add(c *gin.Context) {
	name := c.PostForm("name")
	static := c.PostForm("static")
	if name == "" || static == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	r := models.DB.Begin()
	perm := models.Perm{
		Name:   name,
		Static: static,
	}
	err := models.DB.Create(&perm).Error
	if err != nil {
		r.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	r.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Bind(c *gin.Context) {
	name := c.PostForm("name")
	static := c.PostForm("static")
	if name == "" || static == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	r := models.DB.Begin()
	perm := models.Perm{
		Name:   name,
		Static: static,
	}
	err := models.DB.Create(&perm).Error
	if err != nil {
		r.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	r.Commit()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	office := (page - 1) * size
	query := models.DB.Model(&models.Perm{})

	var count int64
	query.Count(&count)
	var perm models.Perm
	err := query.Offset(office).Limit(size).Find(&perm).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": gin.H{
				"count": count,
				"perm":  perm,
			},
		})
		return
	}
}
